from django.shortcuts import render, redirect

import AppManager.Mysql
from AppManager import views as AMviews
from Logs import views as Logs_views


def login(requests):
    if requests.method == 'GET':
        return render(requests, 'login.html')
    else:
        username = requests.POST['username']
        password = requests.POST['password']

        if username and password:
            sql = "select * from user where user = '%s' and password = '%s'" % (username, password)
            getres = AppManager.Mysql.MysqlPool(sql, 1)
            if getres:
                res = redirect('/index')
                if requests.META.get('HTTP_X_FORWARDED_FOR'):
                    ip = requests.META['HTTP_X_FORWARDED_FOR']
                else:
                    ip = requests.META['REMOTE_ADDR']
                res.set_cookie('user', username, max_age=3600)
                Logs_views.log(username + "登录成功，登录ip为：" + ip, "UserLog", username)
                return res
            else:
                context = {'login_errors': '用户名或密码错误'}
                return render(requests, 'login.html', context)
        else:
            context = {'login_errors': '用户名和密码不能为空'}
            return render(requests, 'login.html', context)


def logout(requests):
    if requests.META.get('HTTP_X_FORWARDED_FOR'):
        ip = requests.META['HTTP_X_FORWARDED_FOR']
    else:
        ip = requests.META['REMOTE_ADDR']
    res = redirect('/login')
    res.delete_cookie('user')  # 清除cookies
    username = requests.COOKIES.get('user')
    Logs_views.log(username + "退出登录，退出IP为：" + ip, "UserLog", username)
    return res
